package com.example.demo.controller;

import com.example.demo.common.AppConstant;
import com.example.demo.common.JsonResult;
import com.example.demo.common.PasswordUtils;
import com.example.demo.common.UserSessionUtils;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import static com.example.demo.common.AppConstant.SESSION_USER_KEY;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/reg")
    public JsonResult reg(User user) {
        if (user == null || !StringUtils.hasLength(user.getPhone()) || user.getPhone().length() != 11) {
            return JsonResult.failure(-1, "非法参数!");
        }

        for (char ch : user.getPhone().toCharArray()) {
            if (!Character.isDigit(ch)) {
                return JsonResult.failure(-1, "非法参数!");
            }
        }
        if (!StringUtils.hasLength(user.getUsername()) || !StringUtils.hasLength(user.getPassword())) {
            return JsonResult.failure(-1, "用户名或密码不能为空!");
        }

        if (user.getUsername().length() < 2 || user.getUsername().length() > 10) {
            return JsonResult.failure(-1, "非法参数!");
        }

        for (char ch : user.getUsername().toCharArray()) {
            if (ch == ' ') {
                return JsonResult.failure(-1, "非法参数!");
            }
        }

        for (char ch : user.getPassword().toCharArray()) {
            if (ch == ' ') {
                return JsonResult.failure(-1, "非法参数!");
            }
        }

        if (userService.getUserByPhone(user.getPhone()) != null) {
            return JsonResult.failure(-2, "该手机号已被注册!");
        }

        // 密码加密
        user.setPassword(PasswordUtils.encrypt(user.getPassword()));
        // 返回受影响的行数
        return JsonResult.success(userService.reg(user));
    }

    @RequestMapping("/login")
    public JsonResult login(String phone, String password, HttpServletRequest request) {
        if (!StringUtils.hasLength(phone) || !StringUtils.hasLength(password)) {
            return JsonResult.failure(-1, "手机号或密码不能为空!");
        }

        // 通过 phone 查询, 拿到 user 对象
        User user = userService.getUserByPhone(phone);
        // 判断用户名和密码是否正确
        if (user == null || !PasswordUtils.check(password, user.getPassword())) {
            return JsonResult.failure(-2, "手机号或密码错误!");
        }
        // 获取 session
        HttpSession session = request.getSession(true);
        // 去掉密码
        user.setPassword("");
        // 存入 session
        session.setAttribute(SESSION_USER_KEY, user);
        // 返回用户信息
        return JsonResult.success(user);
    }

    @RequestMapping("/updatephoto")
    public JsonResult updatePhoto(HttpServletRequest request, @RequestPart("photo") MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        if (!".jpg".equals(fileName) && !".png".equals(fileName)) {
            return JsonResult.failure(-1, "上传头像图片只能是 JPG 或 PNG 格式！");
        }
        String filePath = AppConstant.USER_DIR + "/" + UUID.randomUUID() + fileName;
        file.transferTo(new File(filePath));
        filePath = filePath.substring(filePath.indexOf("/images"));

        // 从session中获取 user
        User user = UserSessionUtils.getUser(request);

        // 更新数据库中的图片路径
        User userTmp = new User();
        userTmp.setId(user.getId());
        userTmp.setPhoto(filePath);
        userService.update(userTmp);
        // 更新 session
        user.setPhoto(filePath);
        HttpSession session = request.getSession(true);
        session.setAttribute(SESSION_USER_KEY, user);
        // 返回图片路径
        return JsonResult.success(filePath);
    }

    @RequestMapping("/updatepwd")
    public JsonResult updatePwd(HttpServletRequest request, String oldPassword, String newPassword) {
        if (!StringUtils.hasLength(oldPassword) || !StringUtils.hasLength(newPassword)) {
            return JsonResult.failure(-1, "非法参数");
        }

        for (char ch : newPassword.toCharArray()) {
            if (ch == ' ') {
                return JsonResult.failure(-1, "非法参数!");
            }
        }

        // 拿到用户对象
        User user = userService.getById(UserSessionUtils.getUserId(request));
        // 判断旧密码是否正确
        if (user == null || !PasswordUtils.check(oldPassword, user.getPassword())) {
            return JsonResult.failure(-2, "旧密码有误!");
        }

        // 新密码加密
        String finalPassword = PasswordUtils.encrypt(newPassword);
        user.setPassword(finalPassword);
        // 返回受影响的行数
        return JsonResult.success(userService.update(user));
    }

    @RequestMapping("/updatephone")
    public JsonResult updatePhone(HttpServletRequest request, String phone) {
        if (!StringUtils.hasLength(phone)) {
            return JsonResult.failure(-1, "非法参数");
        }

        if (userService.getUserByPhone(phone) != null) {
            return JsonResult.failure(-2, "该手机号已被注册!");
        }

        User user = UserSessionUtils.getUser(request);

        // 更新数据库
        User userTmp = new User();
        userTmp.setId(user.getId());
        userTmp.setPhoto(phone);
        int ret = userService.update(userTmp);
        if (ret == 1) {
            // 更新session
            user.setPhoto(phone);
            HttpSession session = request.getSession(true);
            session.setAttribute(SESSION_USER_KEY, user);
        }
        // 返回受影响的行数
        return JsonResult.success(ret);
    }

    @RequestMapping("/updateusername")
    public JsonResult updateUsername(HttpServletRequest request, String username) {
        if (!StringUtils.hasLength(username)) {
            return JsonResult.failure(-1, "非法参数");
        }

        User user = UserSessionUtils.getUser(request);

        // 更新数据库
        User userTmp = new User();
        userTmp.setId(user.getId());
        userTmp.setUsername(username);
        int ret = userService.update(userTmp);
        if (ret == 1) {
            // 更新session
            user.setUsername(username);
            HttpSession session = request.getSession(true);
            session.setAttribute(SESSION_USER_KEY, user);
        }
        // 返回受影响的行数
        return JsonResult.success(ret);
    }

    @RequestMapping("/logout")
    public JsonResult logout(HttpSession session) {
        session.removeAttribute(SESSION_USER_KEY);
        return JsonResult.success(null);
    }
}
